package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// User 有多张 CreditCard，UserID 是外键
type User struct {
	gorm.Model
	CreditCards []CreditCard `gorm:"foreignKey:UserRefer"`
}

type CreditCard struct {
	gorm.Model
	Number    string
	UserRefer uint
}

func main() {
	dsn := "root:root@tcp(192.168.4.111:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Println("err", err)
	}

	// _ = db.AutoMigrate(&CreditCard{})
	//var user = User{}
	//db.Create(&user)
	//
	//db.Create(&CreditCard{
	//	Number:    "12",
	//	UserRefer: user.ID,
	//})
	//db.Create(&CreditCard{
	//	Number:    "34",
	//	UserRefer: user.ID,
	//})

	var user = User{}
	res := db.Preload("CreditCards").First(&user)
	fmt.Println("user", user)
	fmt.Println("res.Error", res.Error)
	fmt.Println("res.RowsAffected", res.RowsAffected)
	fmt.Println("<<==============================>>")

}
